package com.vcc.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.exception.ProgramException;
import com.vcc.data.entity.ClientUserParam;
import com.vcc.data.entity.Role;
import com.vcc.data.mapper.ClientUserParamMapper;
import com.vcc.service.service.ClientUserParamService;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.vcc.data.entity.table.ClientUserParamTableDef.CLIENT_USER_PARAM;
import static com.vcc.data.entity.table.UserTableDef.USER;

@Service
public class ClientUserParamServiceImpl extends ServiceImpl<ClientUserParamMapper, ClientUserParam> implements ClientUserParamService {
    @Override
    public List<ClientUserParam> listByUserId(Long userId) {
        return queryChain().where(CLIENT_USER_PARAM.USER_ID.eq(userId)).list();
    }

    @Override
    public ClientUserParam getByUserIdAndParamId(Long userId, Long clientParamId) {
        return queryChain()
                .where(CLIENT_USER_PARAM.USER_ID.eq(userId))
                .and(CLIENT_USER_PARAM.CLIENT_PARAM_ID.eq(clientParamId))
                .oneOpt()
                .orElseThrow(() -> new ProgramException("参数没有找到"));
    }

    @Override
    public Boolean existsByUserIdAndParamId(Long userId, Long clientParamId) {
        return queryChain()
                .where(CLIENT_USER_PARAM.USER_ID.eq(userId))
                .and(CLIENT_USER_PARAM.CLIENT_PARAM_ID.eq(clientParamId))
                .exists();
    }

    @Override
    public Boolean updateValue(Long id, String value) {
        return updateChain()
                .set(CLIENT_USER_PARAM.VALUE, value)
                .where(CLIENT_USER_PARAM.ID.eq(id))
                .update();
    }

    @Override
    public Integer sumByUserIdAndRole(Long userId, Role role) {
        QueryChain<ClientUserParam> queriedChain = queryChain();
        queriedChain.select("sum(value)").as("total");
        if (role.getHasAllData()){
            queriedChain.leftJoin(USER).on(USER.ID.eq(CLIENT_USER_PARAM.USER_ID));
            queriedChain.where(USER.ID.eq(userId).or(USER.PARENT_ID.eq(userId)));
        }else {
            queriedChain.where(CLIENT_USER_PARAM.USER_ID.eq(userId));
        }
        return queriedChain.oneAs(Integer.class);
    }
}
